import { formatTimeDate } from '../../../utils/vutils'
import { HomeHttp } from '../../../api/home.js'
import { servicePointMap } from '../../../utils/dataMap.js'
import User from "../../../utils/user.js";
import utils from "../../../utils/utils";
import Dialog from '../../../dist/dialog/dialog';
const homeModel = new HomeHttp()
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    serviceCenterId: '',
    activeTimeIndex: -1,
    currentTimeIndex: -1,
    selectSeckillTimeStatus: 0, // 秒杀状态： 1：热抢中  2：已结束  3：未开抢
    seckillSelectStartTimeStr: '', // 当前选择秒杀时间（格式：字符串）
    seckillTimeList: [], // 秒杀时间列表
    seckillGoodsList: [], // 秒杀商品列表
    countTime: 0, // 倒计时
    countTimeDate: {}, // 倒计时 item
    servicePointList: [], // 服务点列表
    servicePointInfo: {}, // 服务点信息
    isShowServiceCenterPopup: false, // 是否显示服务中心弹框
    serverTimestamp: 0,
    latitude: 0, // 维度
    longitude: 0, // 经度
    page: 1,
    pageSize: 10,
    totalNum: 0,
    seckillGoodsContainerHeight: 0 // 秒杀商品容器scroll-view高度
  },

  async initPage(options) {
    this.setNavigationBarColor() // 设置导航栏颜色
    this.initGoodsCategroyHeight() // 设置scroll-viwe高度
    this.setData({
      serviceCenterId: options.id || wx.getStorageSync('servicePointInfo_2').serviceCenterId || ''
    })
    if (this.data.serviceCenterId) {
      this.initSeckillGoods(options)
    } else {
      try {
        await this.httpWxGetLocation()
        await this.httpGetNearbyServicePoint()
        if (!this.data.isShowServiceCenterPopup) {
          this.initSeckillGoods(options)
        }
      } catch {
        await this.httpGetNearbyServicePoint()
        if (!this.data.isShowServiceCenterPopup) {
          this.initSeckillGoods(options)
        }
      }
    }
  },

  async initSeckillGoods(options) {
    await this.httpGetSeckillTimePart() // 获取秒杀时间段
      if (this.data.seckillTimeList.length) {
        const { activeTimeIndex, seckillTimeList } = this.data
        if (options && options.index && options.index >= 0) {
          this.setData({
            currentTimeIndex: options.index,
            seckillSelectStartTimeStr: seckillTimeList[options.index].startTimeStr
          })
        } else {
          this.setData({
            currentTimeIndex: activeTimeIndex,
            seckillSelectStartTimeStr: seckillTimeList[activeTimeIndex].startTimeStr
          })
        }
        await this.httpGetSeckillTimeGoods()
      } else {
        wx.showToast({
          title: '暂无秒杀商品',
          icon: 'none',
          duration: 2000,
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/index/index'
          })
        }, 1000)
      }
  },

  // 初始化商品分类列表容器高度，用于解决 ios 10.2.1 scroll-view滑动问题
  initGoodsCategroyHeight() {
    let self = this
    var query = wx.createSelectorQuery()
    query.select('.seckill-goods-container')
      .boundingClientRect(function (rect) {
        self.setData({
          seckillGoodsContainerHeight: rect.height
        })
      }).exec()
  },

  // 修改服务点
  async onChangeServicePoint (pointInfo) {
    const { servicePointInfo } = this.data
    console.log('servicePointInfo_2', servicePointInfo)
    if (pointInfo.pointId !== servicePointInfo.pointId) {
      this.setData({
        servicePointInfo: pointInfo,
        serviceCenterId: pointInfo.serviceCenterId,
        isShowServiceCenterPopup: false
      })
      wx.setStorageSync('servicePointInfo_2', pointInfo)
      this.initSeckillGoods()
    }
  },

  // 关闭服务点选择列表弹出层，获取第一个服务点作为默认服务点
  onCloseServicePointPopup() {
    this.onChangeServicePoint(this.data.servicePointList[0])
  },

  // 选择服务点
  onSelectServicePoint(event) {
    const { info } = event.detail // 服务站点信息
    this.onChangeServicePoint(info)
  },

  // 设置导航栏颜色
  setNavigationBarColor() {
    wx.setBackgroundColor({
      backgroundColor: '#43B5E9',
    });
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#43B5E9',
    });
  },

  // 倒计时组件 - change
  onCountDownChange(event) {
    this.setData({
      countTimeDate: event.detail
    })
  },

  // 倒计时组件 - finish
  async onCountDownFinish() {
    await this.httpGetSeckillTimePart() // 获取秒杀时间段
    await this.httpGetSeckillTimeGoods()
  },

  // 改变选择的秒杀时间
  async onSeckillTimeChange(event) {
    const { seckillTimeList } = this.data
    const { startTimeStr, endTimestamp, seckillStatus } = event.detail
    let index = seckillTimeList.findIndex(item => item.startTimeStr === startTimeStr)
    this.setData({
      page: 1,
      currentTimeIndex: index,
      seckillSelectStartTimeStr: startTimeStr
    })
    this.httpGetSeckillTimeGoods().then(() => {
      this.setData({
        selectSeckillTimeStatus: seckillStatus,
        countTime: endTimestamp - this.data.serverTimestamp
      })
    })
  },

  onScrollToLower () {
    const { seckillGoodsList, page, totalNum } = this.data
    if (seckillGoodsList.length < totalNum) {
      this.setData({
        page: page + 1
      })
      this.httpGetSeckillTimeGoods()
    }
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: async function () {
    await this.httpGetSeckillTimePart() // 获取秒杀时间段
    await this.httpGetSeckillTimeGoods()
    wx.stopPullDownRefresh()
  },

  // 获取秒杀时间段
  httpGetSeckillTimePart() {
    return homeModel.getSeckillTimePart({
      store_service_id: this.data.serviceCenterId
    }, {
      isNeedResponseTime: true
    }).then(res => {
      let activeIndex = -1
      let serverTimestamp = res.tm * 1000
      let resMap = res.seckill_time.map((item, index) => {
        let startTimestamp = this.formatStrTimeToTimestamp(serverTimestamp, item.start_time)
        let endTimestamp = this.formatStrTimeToTimestamp(serverTimestamp * 1000, item.end_time)
        let timeSeckillDesc = ''
        if (item.status === 3) {
          timeSeckillDesc = '即将开始'
          activeIndex = activeIndex === -1 ? index : activeIndex
        } else if (item.status === 2) {
          timeSeckillDesc = '已结束'
        } else if (item.status === 1) {
          timeSeckillDesc = '热抢中'
          activeIndex = activeIndex === -1 ? index : activeIndex
        }
        return {
          startTimeStr: item.start_time,
          endTimeStr: item.end_time,
          startTimestamp: startTimestamp,
          endTimestamp: endTimestamp,
          seckillStatus: item.status, // 当前时间段秒杀状态
          timeSeckillDesc: timeSeckillDesc
        }
      })
      let resMapLen = resMap.length - 1 > 0 ? resMap.length - 1 : 0
      activeIndex = activeIndex === -1 ? resMapLen : activeIndex
      this.setData({
        seckillTimeList: resMap,
        activeTimeIndex: activeIndex
      })
    })
  },

  // 获取秒杀时间段的商品列表
  httpGetSeckillTimeGoods() {
    const { seckillSelectStartTimeStr, page, pageSize } = this.data
    return homeModel.getSeckillTimeGoods({
      now_time: seckillSelectStartTimeStr || formatTimeDate(new Date(), 'hh:mm'),
      store_service_id: this.data.serviceCenterId,
      page: page,
      pageSize: pageSize
    }, {
      isNeedResponseTime: true
    }).then(res => {
      let resMap = []
      let serverTimestamp = res.tm * 1000
      if (res.seckill_goods) {
        resMap = res.seckill_goods.map(item => {
          return {
            goodsId: item.goods_id, // 商品id
            goodsName: item.goods_title, // 商品名称
            goodSThumbnailImg: item.goods_thumbnail_url, // 商品id
            joinNum: item.sales_volume, // 参与人数
            remindNum: item.goods_subscribe_amount, // 提现人数
            goodsPrice: item.goods_price, // 商品原价
            seckillPrice: item.member_goods_price, // 商品秒杀价
            isSetAlert: item.subscribe_status === 1 ? true : false, // 是否设置提醒： 1已设置提醒 2未设置提醒
            limitNum: item.stock_amount // 限量（库存）
          }
        })
      }
      const { currentTimeIndex, seckillTimeList } = this.data
      let seckillStatus = seckillTimeList[currentTimeIndex].seckillStatus
      let nowTimestamp = serverTimestamp
      let endTimestamp = seckillTimeList[currentTimeIndex].endTimestamp
      if (seckillStatus === 1 && endTimestamp > nowTimestamp) {
        this.setData({
          seckillGoodsList: resMap,
          totalNum: res.total,
          selectSeckillTimeStatus: seckillStatus,
          countTime: endTimestamp - nowTimestamp,
          serverTimestamp: serverTimestamp
        })
      } else {
        this.setData({
          seckillGoodsList: resMap,
          totalNum: res.total,
          selectSeckillTimeStatus: seckillStatus,
          serverTimestamp: serverTimestamp
        })
      }
    })
  },

  // 格式化字符串时间为时间戳
  formatStrTimeToTimestamp(time, str) {
    let currentYMD = formatTimeDate(new Date(time), 'yyyy/MM/dd')
    let fullStrTime = `${currentYMD} ${str}`
    return new Date(fullStrTime).getTime()
  },

  // 获取地理位置信息
  httpWxGetLocation() {
    let self = this
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          self.setData({
            longitude: res.longitude, // 经度
            latitude: res.latitude // 维度
          })
          resolve(res)
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
  },

  // 获取附近服务点
  httpGetNearbyServicePoint() {
    const { longitude, latitude } = this.data; // 经纬度信息
    return homeModel.getNearbyServicePoint({
      lng: longitude, // 经度
      lat: latitude, // 纬度
      page: 1,
      page_size: 4
    }).then((res) => {
      // 1. 判断服务点是否超过 1个
      // 2. 如果超过1个服务点，弹窗供用户选择，如果只有1个服务点，默认获取，不弹窗选择
      let isShowService = res.service_point.length > 1
      let servicePointListArr = servicePointMap(res.service_point) // 服务站列表
      !isShowService && wx.setStorageSync('servicePointInfo_2', servicePointListArr[0])
      this.setData({
        servicePointList: servicePointListArr, // 服务站信息
        servicePointInfo: isShowService ? {} : servicePointListArr[0],
        serviceCenterId: isShowService ? '' : servicePointListArr[0].serviceCenterId,
        isShowServiceCenterPopup: isShowService
      })
    })
  },

  // 用户点击右上角分享
  onShareAppMessage: function () {
    let _param, pages, currentPage;
    let nickName = app.globalData.userInfo && app.globalData.userInfo.nickname ? app.globalData.userInfo.nickname : ''
    let nickNameText = nickName ? `${nickName}@您，` : ''
    let _share = {
      title: `${nickNameText}巷友限量秒杀专区，天天抢特价商品`,
      path: `/pages/home/seckillDetails/seckillDetails`,
      image: `${this.data.static_host}/images/share/seckill.png`
    };
    let channel = User.getShareParam(0);
    if (!_share.title) {
      _share['title'] = '快来领取优惠券吧';
    }
    if (!_share.url) {
      pages = getCurrentPages();
      currentPage = pages[pages.length - 1];
      _share['url'] = currentPage.route;
    }
    if (_share['url'].indexOf('?') === -1) {
      _share['url'] += '?v=' + utils.version;
    }
    if (channel.hasOwnProperty('ekey') && channel.ekey && _share['url'].indexOf('ekey') === -1) {
      _share['url'] += '&ekey=' + channel['ekey'];
    }
    if (channel.hasOwnProperty('shareUid') && channel.shareUid > 0 && _share['url'].indexOf('uid') === -1) {
      _share['url'] += '&uid=' + channel['shareUid'];
    }
    _param = {
      title: _share['title'],
      path: _share['url']
    };
    if (_share['image']) {
      _param['imageUrl'] = _share['image'];
    }
    this.isShareLoading = true;
    utils.log('分享参数', _param, 'channel:', channel);
    return _param;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  }
})
